package top.anka1.fxgui;

import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.stage.Stage;
import top.anka1.ims.ZooManagementSystem.*;
/** This class is the controller for the AddAnimal.fxml file.
 * It handles the logic for adding a new animal to a zoo.
 * @author Anka
 */
public class AddAnimalController {
    Stage stage;
    Zoo destinationZoo;
    @FXML
    private Label addAnimalTitle;
    @FXML
    private TextField addAnimalName;
    @FXML
    private TextField addAnimalSpecies;
    @FXML
    private TextField addAnimalAge;

    public void setData(Stage stage, Zoo destinationZoo) {
        this.stage = stage;
        this.destinationZoo = destinationZoo;
        addAnimalTitle.setText("Add Animal to " + destinationZoo.getName());
    }
    private void showError(Stage stage, String title, String HeaderText, String contentText) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.initOwner(stage);
        alert.setTitle(title);
        alert.setHeaderText(HeaderText);
        alert.setContentText(contentText);
        alert.showAndWait();
    }
    @FXML
    public void confirmAddAnimal() {
        String name = addAnimalName.getText();
        String species = addAnimalSpecies.getText();
        String ageText = addAnimalAge.getText();
        if (name.isEmpty() || species.isEmpty() || ageText.isEmpty()) {
            showError(this.stage, "Input Error", "Missing Information", "Please fill in all fields.");
            return;
        }

        try {
            int age = Integer.parseInt(ageText);
            if (age < 0) {
                throw new NumberFormatException("Age cannot be negative.");
            }
            Animal newAnimal = new Animal(name, species, age);
            // Add the new animal to the zoo (assuming you have a method for this)
            destinationZoo.addAnimal(newAnimal);
            Alert successAlert = new Alert(Alert.AlertType.INFORMATION);
            successAlert.initOwner(this.stage);
            successAlert.setTitle("Success");
            successAlert.setHeaderText(null);
            successAlert.setContentText("Animal added successfully!");
            successAlert.showAndWait();
        } catch (NumberFormatException e) {
            showError(this.stage, "Invalid age", "Invalid age. Please enter a valid number for age.", "Error: " + e.getMessage());
        }
    }
}
